package com.haierCamera.customapplication.ui;

import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.Constants;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.api.repo.UserRepo;
import com.haierCamera.customapplication.common.Resource;
import com.haierCamera.customapplication.databinding.HzklActivityMainBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.custom.BottomNavigationViewHelper;
import com.haierCamera.customapplication.ui.mediaplay.fragment.MediaPlayFragment;
import com.haierCamera.customapplication.utils.AppManager;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.android.ActivityManager;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;
import com.haierCamera.customapplication.utils.android.SystemUIHelper;
import com.tencent.bugly.beta.Beta;

import java.util.Timer;
import java.util.TimerTask;

import javax.inject.Inject;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;

import dagger.Lazy;

public class MainActivity extends BaseActivity {
    HzklActivityMainBinding binding;

    @Inject
    Lazy<NavigationController> navigationController;
    @Inject
    ApiService apiService;
    @Inject
    Lazy<HttpErrorProcess> errorProcessLazy;
    @Inject
    UserRepo repo;

    private static boolean mBackKeyPressed = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SystemUIHelper.setFullWindow(getWindow());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            SystemUIHelper.setStatusBarColor(getWindow(), Color.TRANSPARENT);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            SystemUIHelper.setStatusBarTextColor(getWindow(), true);
        }

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_main);
        binding.navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
        BottomNavigationViewHelper.disableAnim(binding.navigation);
        if (null != savedInstanceState) {
            int fragment = savedInstanceState.getInt("fragment", 1);
            navigationController.get().navigationTo(fragment);
        } else {
            navigationController.get().nvHome();
        }

        binding.setLifecycleOwner(this);
        //背景选中状态去掉
        binding.navigation.setItemIconTintList(null);

        getHandler().post(() -> Beta.checkUpgrade(false, false));
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("fragment", navigationController.get().getCurrentFragmentKey());
    }

    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = item -> {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                if (navigationController.get().getCurrentFragmentKey() == 1) {
                    return true;
                }
                navigationController.get().nvHome();
                return true;
            case R.id.navigation_self:
                if (navigationController.get().getCurrentFragmentKey() == 3) {
                    return true;
                }
                navigationController.get().nvSelf();
                return true;
            case R.id.navigation_msg:
                if (navigationController.get().getCurrentFragmentKey() == 2) {
                    return true;
                }
                navigationController.get().nvMsg();
                return true;
            default:
                return false;
        }
    };

    public void getLcToken() {
        ResourceConvertUtils.convertToResource(apiService.getLcToken())
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            errorProcessLazy.get().process(resource);

                            break;
                        case SUCCESS:
                            if (resource.data.toString().contains("lcToken=")) {

                                String s = resource.data.toString();
                                String s1 = s.substring(s.indexOf("lcToken="));
                                String s2 = s1.substring(0, s1.indexOf("}"));
                                s2 = s2.substring(8, s2.length());

                                SharedPreferencesUtils.saveString(Constants.LCTOKEN, s2 + "");
                                Business.getInstance().setToken(s2 + "");
                            }
                            initPush();
                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    @Override
    public void onBackPressed() {
        if (!mBackKeyPressed) {
            toast("再按一次退出程序");
            mBackKeyPressed = true;
            new Timer().schedule(new TimerTask() {//延时两秒，如果超出则擦错第一次按键记录
                @Override
                public void run() {
                    mBackKeyPressed = false;
                }
            }, 2000);
        } else {//退出程序
            AppManager.getAppManager().finishAllActivity();
            ActivityManager.getInstance().clearAll();
            finish();

        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        String user = SharedPreferencesUtils.getString(Constants.SP_USER_TOKEN, null);
        if (TextUtils.isEmpty(user)) {
            return;
        }
        getLcToken();

    }

    String pushId = "";

    private void initPush() {
        String CID = SharedPreferencesUtils.getString(Constants.SP_CID, "");
        String brand = Build.MANUFACTURER.toLowerCase();
        if (brand.contains("huawei")) {
            pushId = "huawei";
        } else if (brand.contains("mi")) {
            pushId = "mi";
        } else if (brand.contains("oppo")) {
            pushId = "oppo";
        } else if (brand.contains("vivo")) {
            pushId = "vivo";
        } else {
            pushId = "mi";
        }
        repo.registerSend(pushId, CID).observe(this, objectResource -> {
            switch (objectResource.status) {
                case LOADING:
                    break;
                case ERROR:
                    Log.i("个推注册", "失败" + objectResource.errorMessage);
                    break;
                case SUCCESS:
                    Log.i("个推注册", "成功 1");
                    break;
            }
        });
    }

}
